<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use think\Cache;
use think\Db;
use PDO;
use think\Log;
use wxpay\lspay;
use wxpay\wxpay;
use alipay\Alipay;
use epay\epay;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;

class Order extends Api
{
    protected $noNeedRight = '*';
    protected $noNeedLogin = ['notifyx','notifyxThree','epaysqfhnotifyx','sqfhnotifyx'];
    /**
     * 获取当前用户是否有订单
     */
    public function getUserOrder() {
        //获取盲盒ID
        $id = input('id');
        $where['user_id'] = $this->auth->id;
        $where['status'] = 'used';
        $where['boxfl_id'] = $id;
        $info = Db::table('box_order')->where($where)->find();
        $res = $info ? 1 : 2;
        if($res){
            $this->success('是否有盲盒订单', $res);
        }
    }
      public function getUserOrderIndex() {
        //获取新人试玩盲盒ID
        $info = Db::table('box_boxfl')->field("id")->where('single_switch',1)->find();
        if(!$info){
            $this->error("没有新人试玩");
        }
        $where['user_id'] = $this->auth->id;
        $where['status'] = 'used';
        $where['boxfl_id'] = $info['id'];
        $info = Db::table('box_order')->where($where)->find();
        $res = $info ? 1 : 2;
        if($res){
            $this->success('是否有盲盒订单', $res);
        }
    }
    /**
     * 获取商城订单
     */
    public function getOrders()
    {
        $where  = [];
        //状态为1是待付款
        if (input('zt') == 1) {
            $where = [
                'status' => 'unpay'
            ];
        } else if (input('zt') == 2) {
            $where = [
                'status' => 'used'
            ];
        } else if (input('zt') == 3) {
            $where = [
                'status' => 'refund'
            ];
        } else if (input('zt') == 4) {
            $where = [
                'status' => 'ywc'
            ];
        }
        $order = Db::table('box_shoporder')->where('user_id', $this->auth->id)->where($where)->order('create_time DESC')->select();
        foreach ($order as &$order_v) {
            $order_v['image'] = cdnurl($order_v['image'], true);
            if ($order_v['status'] == 'unpay') {
                $order_v['status'] = '待支付';
            } else if ($order_v['status'] == 'used') {
                $order_v['status'] = '待发货';
            } else if ($order_v['status'] == 'refund') {
                $order_v['status'] = '已发货';
            } else if ($order_v['status'] == 'ywc') {
                $order_v['status'] = '已完成';
            } else if ($order_v['status'] == 'undei') {
                $order_v['status'] = '已关闭';
            }
            //快递公司:yuantong=圆通速递,yunda=韵达快递,shentong=申通快递,zhongtong=中通快递,jtexpress=极兔速递,shunfeng=顺丰速运,youzhengguonei=邮政快递,ems=EMS,jd=京东物流,debangkuaidi=德邦快递
            switch ($order_v['kdgs']) {
                case 'yuantong':
                    $order_v['kdgs_v'] = '圆通速递';
                    break;
                case 'yunda':
                    $order_v['kdgs_v'] = '韵达快递';
                    break;
                case 'shentong':
                    $order_v['kdgs_v'] = '申通快递';
                    break;
                case 'zhongtong':
                    $order_v['kdgs_v'] = '中通快递';
                    break;
                case 'jtexpress':
                    $order_v['kdgs_v'] = '极兔速递';
                    break;
                case 'shunfeng':
                    $order_v['kdgs_v'] = '顺丰速运';
                    break;
                case 'youzhengguonei':
                    $order_v['kdgs_v'] = '邮政快递';
                    break;
                case 'ems':
                    $order_v['kdgs_v'] = 'EMS';
                    break;
                case 'jd':
                    $order_v['kdgs_v'] = '京东物流';
                    break;
                case 'debangkuaidi':
                    $order_v['kdgs_v'] = '德邦快递';
                    break;
                default:
                    break;
            }
        }

        $this->success('订单数据', $order);
    }
    /**
     * 查看单个订单详情
     */
    public function getOrder()
    {
        $order =  Db::table('box_shoporder')->where('out_trade_no', input('ooid'))->find();
        $order['image'] = cdnurl($order['image'], true);
        if ($order['status'] == 'unpay') {
            $order['status'] = '待支付';
        } else if ($order['status'] == 'used') {
            $order['status'] = '待发货';
        } else if ($order['status'] == 'refund') {
            $order['status'] = '已发货';
        } else if ($order['status'] == 'ywc') {
            $order['status'] = '已完成';
        } else if ($order['status'] == 'undei') {
            $order['status'] = '已关闭';
        }
        $this->success('订单数据', $order);
    }
    /**
     * 获取仓库数据
     */
    public function getMhOrder()
    {
        //根据用户ID查询开箱记录
        $where = [];
        if (input('status') == 1) {
            //代表是已回收
            $where = [
                'status' => 'exchange'
            ];
        } else {
            $where = [
                'status' => 'bag'
            ];
        }
        $list = Db::table('box_prize_record')->where('user_id', $this->auth->id)->where($where)->order('create_time DESC')->select();
        if (empty($list)) {
            $this->success('未找到数据', $list);
        }
        $id = [];
        foreach ($list as &$list_v) {
            $list_v['goods_image'] = cdnurl($list_v['goods_image'], true);
            $list_v['hstime'] = date('Y-m-d H:i:s', $list_v['hstime']);
            $id[] = $list_v['goods_id'];
            if ($list_v['status'] == 'bag') {
                $list_v['status_v'] = '盒柜';
            } else if ($list_v['status'] == 'exchange') {
                $list_v['status_v'] = '已兑换';
            } else if ($list_v['status'] == 'delivery') {
                $list_v['status_v'] = '申请发货';
            } else if ($list_v['status'] == 'received') {
                $list_v['status_v'] = '已收货';
            }
        }

        $shops = Db::table('box_mhgoods')->where('id', 'in', $id)->select();
        foreach ($list as &$l) {
            foreach ($shops as $shop) {
                if ($l['goods_id'] == $shop['id']) {
                    $l['luyck'] = $shop['luckycoin'];
                    $l['goods_name_en'] = $shop['goods_name_en'];
                }
            }
        }
        $cardjl = Db::table('box_card_list')->where('user_id', $this->auth->id)->find();
        if (empty($cardjl)) {
            $this->success('查询成功', ['list' => $list, 'cck' => '0']);
        } else {
            $this->success('查询成功', ['list' => $list, 'cck' => '1']);
        }
    }
    
    // 设置参数
    private function getOptions()
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = $s['appId'];
        $options->merchantPrivateKey = $s['rsaPrivateKey'];
        $options->alipayPublicKey = $s['alipayrsaPublicKey'];
        return $options;
    }
    
    /**
     * 申请发货接口
     */
    public function sqfh()
    {
        $s = Db::table('box_prize_record')->where('id', input('id'))->find();
        $addres = Db::table('box_user_address')->where('id', input('addresid'))->find();
        // $ooid = 'ALDMH' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        list($msec, $sec) = explode(' ', microtime());
        $num = md5(floatval($msec) + floatval($sec).time());
        $ooid = 'ALDMH' . date('Ymd') . substr(md5(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))).$num), 0, 8);
        $post = input();
        //当运费为0时
          $user = User::where('id',$this->auth->id)->find();
        if ($s['delivery_fee'] == 0) {
            $data = [
                'shop_id' => $s['goods_id'],
                'shop_name' => $s['goods_name'],
                'image' => $s['goods_image'],
                'num' => 1,
                'user_id' => $this->auth->id,
                'pay_method' => 'sqfh',
                'out_trade_no' => $ooid,
                'status' => 'used',
                'address' => $addres['province'] . $addres['city'] . $addres['area'] . $addres['detail'],
                'username' => $addres['name'],
                'mobile' => $addres['mobile'],
                'delivery_fee' => 0,
                'price' => $s['goods_rmb_price'],
                'pay_time' => time(),
                 'anchor_switch'=> $user->anchor_switch
            ];
            $ret = Db::table('box_shoporder')->insert($data);
            if (empty($ret)) {
                $this->error('申请失败');
            }
            Db::table('box_prize_record')->where('id', input('id'))->update(['status' => 'delivery']);
            $this->success('发货成功');
        } else {
            if ($post['terminal'] == 0) {
                $data = [
                    'shop_id' => $s['goods_id'],
                    'shop_name' => $s['goods_name'],
                    'image' => $s['goods_image'],
                    'num' => 1,
                    'user_id' => $this->auth->id,
                    'pay_method' => 'sqfh',
                    'out_trade_no' => $s['order_id'],
                    'status' => 'unpay',
                    'address' => $addres['province'] . $addres['city'] . $addres['area'] . $addres['detail'],
                    'username' => $addres['name'],
                    'mobile' => $addres['mobile'],
                    'delivery_fee' => $s['delivery_fee'],
                    'price' => $s['goods_rmb_price'],
                ];
                $ret = Db::table('box_shoporder')->insert($data);
                //如果为0就是H5
                $epay = new epay;
                if ($post['payfs'] == 'alipay') {
                    $alipay = new Alipay();
                    $notice = $this->request->domain() . '/index.php/api/order/sqfhnotifyx';
                    $alipay->h5pay('支付运费', $s['order_id'], $s['delivery_fee'], $notice,$this->request->domain() . '/h5/#/pages/mall/paySuccexx');   
                    
                }else if($post['payfs'] == 'wechat'){
                    $notifyurl = $this->request->domain() . '/index.php/api/pay/epaysqfhnotifyx';
                    $epay->goePay($s['order_id'], 'wechat', '支付运费', $s['delivery_fee'],$notifyurl,$this->request->domain() . '/h5/#/pages/mall/paySuccexx');
                }
            } else if ($post['terminal'] == 1) {
                $data = [
                    'shop_id' => $s['goods_id'],
                    'shop_name' => $s['goods_name'],
                    'image' => $s['goods_image'],
                    'num' => 1,
                    'user_id' => $this->auth->id,
                    'pay_method' => 'sqfh',
                    'out_trade_no' => $s['order_id'],
                    'status' => 'unpay',
                    'address' => $addres['province'] . $addres['city'] . $addres['area'] . $addres['detail'],
                    'username' => $addres['name'],
                    'mobile' => $addres['mobile'],
                    'delivery_fee' => $s['delivery_fee'],
                    'price' => $s['goods_rmb_price'],
                ];
                $ret = Db::table('box_shoporder')->insert($data);
                
                if ($post['payfs'] == 'alipay') {
                    // $price = 0.01;
                    $notice = $this->request->domain() . '/index.php/api/order/sqfhnotifyx';
                    Factory::setOptions($this->getOptions());
                    $result = Factory::payment()->common()
                        ->asyncNotify($notice)
                        ->create("支付运费", $s['order_id'],$s['delivery_fee'], $this->auth->ali_mini_userid);
                    if (!empty($result->code) && $result->code == 10000) { 
                        $this->success('支付成功',['ooid'=>$ooid,'tradeNo'=>$result->tradeNo]);
                    } else {
                        $this->error('支付异常',['ooid'=>$ooid]);
                    }
                } else {
                    // 如果为1就是小程序
                    $payWay = Cache::get("pay_way");
                    if(!$payWay){
                        $payWay = Db::table("box_setting")->where("id",1)->column("pay_way");
                        $payWay = $payWay[0];
                    }
                    //1.微信原生支付；2.联速支付
                    if($payWay == 1){
                        // $this->payJoinfee('支付运费', $s['order_id'], $s['delivery_fee']);
                         $user = Db::table('box_user')->where('id',$this->auth->id)->find();
                         if ($s['delivery_fee'] > $user['balance']) {
                            $this->error('支付失败，您的余额不足'); exit();
                        }
                         $ret = Db::table('box_balancelog')->insert([
                            'user_id'=> $this->auth->id,
                            'beforemoney'=> $user['balance'],
                            'aftermoney'=> $user['balance'] - $s['delivery_fee'],
                            'money'=> $s['delivery_fee'],
                            'bgexplain' => 'gmyf',
                            'addtime' => time(),
                      ]);
                        Db::table('box_user')->where('id', $this->auth->id)->update(['balance' => $user['balance'] - $s['delivery_fee']]);
                        Db::table('box_shoporder')->where('out_trade_no', $s['order_id'])->update(['status' => 'used', 'pay_time' => time()]);
                        Db::table('box_prize_record')->where('order_id',$s['order_id'])->update(['status' => 'delivery']);
                        return $this->success('支付成功');
                    }else{
                        return $this->error("联速支付暂未开通");
                    }   
                }
            } else if ($post['terminal'] == 2) {
                $data = [
                    'shop_id' => $s['goods_id'],
                    'shop_name' => $s['goods_name'],
                    'image' => $s['goods_image'],
                    'num' => 1,
                    'user_id' => $this->auth->id,
                    'pay_method' => 'alipay',
                    'out_trade_no' => $s['order_id'],
                    'status' => 'unpay',
                    'address' => $addres['province'] . $addres['city'] . $addres['area'] . $addres['detail'],
                    'username' => $addres['name'],
                    'mobile' => $addres['mobile'],
                    'delivery_fee' => $s['delivery_fee'],
                    'price' => $s['goods_rmb_price'],
                ];
                $ret = Db::table('box_shoporder')->insert($data);
                //如果为2就是APP
                $alipay = new Alipay();
                $notice = $this->request->domain() . '/index.php/api/order/sqfhnotifyx';
                $alipay->pay('支付运费',$s['order_id'],$s['delivery_fee'],$notice);
            }
        }
    }
    
    // 支付宝发货回调
    public function sqfhnotifyx() {
        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
            Db::table('box_shoporder')->where('out_trade_no', $_POST['out_trade_no'])->update([
                'status' => 'used', 
                'pay_time' => time(), 
                'alipay_trade_no' => $_POST['trade_no']
            ]);
            Db::table('box_prize_record')->where('order_id', $_POST['out_trade_no'])->update(['status' => 'delivery']);
            echo 'success';
        } else {
            echo 'fail';
        }
    }
    
    //支付费用
    public function payJoinfee($name, $ooid, $price)
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $appid = $s['mpappid'];
        $openid = $this->auth->wx_mini_openid;
        $mch_id = $s['payid'];
        $key = $s['paykey'];
        import('Weixin.Lib.WeixinPay');
        $notifyurl = $this->request->domain() . '/index.php/api/order/notifyx';
        $weixinpay = new wxpay($appid, $openid, $mch_id, $key, $name, $ooid, $price, $notifyurl);
        $return = $weixinpay->pay();
        $this->success('支付', ['data' => $return, 'ooid' => $ooid]);
    }

    //联速三方支付费用
    public function payJoinfeeThree($name, $ooid, $price)
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $mch_id = $s['lspay_mch_no'];
        $key = $s['lspay_key'];
        $app_id = $s['lspay_app_id'];
        $openid = $this->auth->wx_mini_openid;
        $notifyurl = $this->request->domain() . '/index.php/api/order/notifyxThree';
        $weixinpay = new lspay($openid, $mch_id, $key, $app_id, $name, $ooid, $price, $notifyurl);
        $return = $weixinpay->pay();
        $this->success('支付', ['data' => $return, 'ooid' => $ooid]);
    }
    //第三方联速回调
    public function notifyxThree()
    {
        $postData = $_POST;
        log::write(["msg"=>"回调参数","data"=>$_POST],"log");
        if ($postData) {
            //如果成功返回了
            $out_trade_no = $postData['mch_order_no'];
            $transaction_id = $postData['pay_order_id'];
            $pedata = Db::table('box_prize_record')->field("id")->where('out_trade_no', $out_trade_no)->find();
            if(!$pedata){
                $this->handle($out_trade_no,$transaction_id);
            }
        }
        echo "ok";
    }
    public function notifyx()
    {
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true); //转成数组，
        log::write(["msg"=>"发货回调返回参数","res"=>$result],"log");
        if ($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            $transaction_id = $result['transaction_id'];
            $this->handle($out_trade_no,$transaction_id);
        }
        $xml = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        echo $xml;
    }
    //订单处理
    public function handle($ooid, $tranid)
    {
        Log::write(["msg"=>"发货回调","ooid"=>$ooid]);
        Db::startTrans();
        try {
            Db::table('box_shoporder')->where('out_trade_no', $ooid)->update(['status' => 'used', 'pay_time' => time(), 'transaction_id' => $tranid]);
            Db::table('box_prize_record')->where('order_id',$ooid)->update(['status' => 'delivery']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }
}
